package com.ruoyi.web.controller.bl;

import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.bl.domain.BlGoods;
import com.ruoyi.bl.service.IBlGoodsService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.bl.domain.BlGoodsStore;
import com.ruoyi.bl.service.IBlGoodsStoreService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品库存Controller
 * 
 * @author ruoyi
 * @date 2024-11-21
 */
@RestController
@RequestMapping("/bl/goodsStore")
public class BlGoodsStoreController extends BaseController
{
    @Autowired
    private IBlGoodsStoreService blGoodsStoreService;

    @Autowired
    private IBlGoodsService blGoodsService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询商品库存列表
     */
    @PreAuthorize("@ss.hasPermi('bl:goodsStore:list')")
    @GetMapping("/list")
    public TableDataInfo list(BlGoodsStore blGoodsStore)
    {
        startPage();
        List<BlGoodsStore> list = blGoodsStoreService.selectBlGoodsStoreList(blGoodsStore);
        return getDataTable(list);
    }

    /**
     * 导出商品库存列表
     */
    @PreAuthorize("@ss.hasPermi('bl:goodsStore:export')")
    @Log(title = "商品库存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BlGoodsStore blGoodsStore)
    {
        List<BlGoodsStore> list = blGoodsStoreService.selectBlGoodsStoreList(blGoodsStore);
        ExcelUtil<BlGoodsStore> util = new ExcelUtil<BlGoodsStore>(BlGoodsStore.class);
        util.exportExcel(response, list, "商品库存数据");
    }

    /**
     * 获取商品库存详细信息
     */
    @PreAuthorize("@ss.hasPermi('bl:goodsStore:query')")
    @GetMapping(value = "/{storeId}")
    public AjaxResult getInfo(@PathVariable("storeId") Long storeId)
    {
        return success(blGoodsStoreService.selectBlGoodsStoreByStoreId(storeId));
    }

    /**
     * 新增商品库存
     */
    @PreAuthorize("@ss.hasPermi('bl:goodsStore:add')")
    @Log(title = "商品库存", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BlGoodsStore blGoodsStore)
    {
        return toAjax(blGoodsStoreService.insertBlGoodsStore(blGoodsStore));
    }

    /**
     * 修改商品库存
     */
    @PreAuthorize("@ss.hasPermi('bl:goodsStore:edit')")
    @Log(title = "商品库存", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BlGoodsStore blGoodsStore)
    {
        return toAjax(blGoodsStoreService.updateBlGoodsStore(blGoodsStore));
    }

    /**
     * 删除商品库存
     */
    @PreAuthorize("@ss.hasPermi('bl:goodsStore:remove')")
    @Log(title = "商品库存", businessType = BusinessType.DELETE)
	@DeleteMapping("/{storeIds}")
    public AjaxResult remove(@PathVariable Long[] storeIds)
    {
        return toAjax(blGoodsStoreService.deleteBlGoodsStoreByStoreIds(storeIds));
    }

    @PreAuthorize("@ss.hasPermi('bl:goodsStore:list')")
    @GetMapping("/getSupplierStoreList")
    public AjaxResult getSupplierStoreList(BlGoodsStore blGoodsStore)
    {
        long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        if(sysUser.getSupplierId() == null){
            return error("请先在用户管理配置供应商");
        }
        blGoodsStore.setSupplierId(sysUser.getSupplierId());
        List<BlGoodsStore> list = blGoodsStoreService.selectBlSupplierStoreList(blGoodsStore);
        return success(list);
    }

    @PreAuthorize("@ss.hasPermi('bl:goodsStore:edit')")
    @PutMapping("/stockReturn")
    public AjaxResult stockReturn(@RequestBody BlGoodsStore blGoodsStore)
    {
        if(blGoodsStore.getStoreId() == null){
            return error("库存ID不能为空");
        }
        BlGoodsStore tmp = new BlGoodsStore();
        tmp.setStoreId(blGoodsStore.getStoreId());
        tmp.setStatus(2);
        return toAjax(blGoodsStoreService.updateBlGoodsStore(tmp));
    }

    /**
     * 新增商品库存
     */
    @Anonymous
    //@PreAuthorize("@ss.hasPermi('bl:goodsStore:add')")
    //@Log(title = "商品库存", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/scanAddStore",method= RequestMethod.POST)
    public String scanAddStore(HttpServletRequest request) throws IOException {
            BufferedReader br = request.getReader();
            String str;
            StringBuilder wholeStr = new StringBuilder();
            while((str = br.readLine()) != null){
                wholeStr.append(str);
            }
            //System.out.println(wholeStr);
            //System.out.println("按参数获取");
            String result = wholeStr.toString().replace("\r", "").replace("\n", "") ;

            String[] params = result.split("&&") ;

            String[] param1 = params[0].split("=") ;
            String vgdecoderesult = param1[1] ;

            String[] param2 = params[1].split("=") ;
            String devicenumber = param2[1] ;
            //String storeSn = blGoodsStore.getStoreSn();
            String storeSn = vgdecoderesult;
            System.out.println("storeSn:"+storeSn);
            if(storeSn.length() !=11){
                //return error("商品条码不是11位");
                //System.out.println("商品条码不是11位");
                return "code=商品条码不是11位";
            }
            String goodsSn = storeSn.substring(0,6);
            BlGoods blGoods = blGoodsService.findBlGoodsByGoodsSn(goodsSn);
            if(blGoods == null){
                //return error("商品不存在");
                //System.out.println("商品不存在");
                return "code=商品不存在";
            }
            int isOnSale = blGoods.getIsOnSale();
            if(isOnSale ==0 ){
                //return error("商品不允许上架");
                System.out.println("商品不允许上架");
                //return "code=商品不允许上架";
            }
//        long deptId = blGoods.getDeptId();
//        if(deptId != getDeptId()){
//            return error("商品与商户不匹配");
//        }
            long goodsId = blGoods.getGoodsId();
            long deptId = blGoods.getDeptId();
            long supplierId = blGoods.getSupplierId();
            int saleUnit = blGoods.getSalesUnit();
            BigDecimal goodsWeigth = new BigDecimal(0.00);
//            if(saleUnit != 2){
//                goodsWeigth = new BigDecimal(Integer.parseInt(storeSn.substring(6,9)));
//            }
            goodsWeigth = new BigDecimal(Integer.parseInt(storeSn.substring(6,9)));
            BigDecimal goodsUprice = blGoods.getGoodsUprice();

            //查询当日已经上架.
            BlGoodsStore gsTmp = blGoodsStoreService.findBlGoodsStoreIfLaunch(storeSn);
            if(gsTmp != null){
                //return error("已完成入库，无需重复扫码");
                //System.out.println("已完成入库，无需重复扫码");
                return "code=已完成入库，无需重复扫码";
            }

            BlGoodsStore gs = new BlGoodsStore();
            gs.setDeptId(deptId);
            gs.setSupplierId(supplierId);
            gs.setGoodsId(goodsId);
            gs.setStoreSn(storeSn);
            gs.setStoreCount(1);
            gs.setSalesUnit(saleUnit);
            gs.setGoodsWeight(goodsWeigth);
            gs.setGoodsPrice(goodsUprice);
            //gs.setCreateBy(getUsername());
            blGoodsStoreService.insertBlGoodsStore(gs);
            //System.out.println("code=0000");
            return "code=0000";
        }
}
